﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using StackExchange.Redis;

namespace NetCoreCMS.Web.Areas.Admin.Controllers
{
    public class Shop_EditController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Finance/shop_edit.cshtml";
        private string action = CMSEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;
        private string error = string.Empty;
        public IShopService _shop { get; set; }
        public IShop_categoryService _shop_category { get; set; }
        public IUsersService _users { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ActionResult result = View(EDIT_RESULT_VIEW);
            action = Request.Query["action"];
            //如果是编辑或复制则检查信息是否存在
            if (action == CMSEnums.ActionEnum.Edit.ToString() || action == CMSEnums.ActionEnum.Copy.ToString() || action == CMSEnums.ActionEnum.View.ToString())
            {
                int.TryParse(Request.Query["id"], out this.id);
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back");
                    filterContext.Result = result;
                    return;
                }
                if (!_shop.Exists(this.id))
                {
                    JscriptMsg("信息不存在或已被删除！", "back");
                    filterContext.Result = result;
                    return;
                }
            }
            //保存参数
            ViewBag.Action = this.action;
            ViewBag.Id = this.id.ToString();
        }

        // GET: /admin/Article_Edit/
        public ActionResult Index()
        {
            ChkAdminLevel("shop_list", CMSEnums.ActionEnum.View.ToString()); //检查权限
            TreeBind(); //绑定类别
            if (action == CMSEnums.ActionEnum.Edit.ToString())
            {
                ShowInfo(this.id);
            }
            else
            {
                NetCoreCMS.Models.Shop model = new NetCoreCMS.Models.Shop();
                model.sort_id = 99;
                ViewData["model"] = model;
            }
            return View(WEB_VIEW);
        }

        [HttpPost]
        public ActionResult SubmitSave(string txtContent)
        {
            ActionResult result = View(EDIT_RESULT_VIEW);
            if (action == CMSEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("shop_list", CMSEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id, txtContent))
                {
                    JscriptMsg("保存过程中发生错误啦！", error);
                    return result;
                }
                JscriptMsg("修改信息成功！", "../shop_list/index");
            }
            else //添加
            {
                ChkAdminLevel("shop_list", CMSEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd(txtContent))
                {
                    JscriptMsg("保存过程中发生错误！", error);
                    return result;
                }
                JscriptMsg("添加信息成功！", "../shop_list/index?");
            }
            return result;
        }

        #region 绑定类别=================================
        private void TreeBind()
        {
            var dt = _shop_category.GetList(0);
            List<SelectListItem> categoryList = new List<SelectListItem>() {
             new SelectListItem(){ Text="请选择类别...", Value=""}
          };
            foreach (Shop_category dr in dt)
            {
                string Id = dr.id.ToString();
                int ClassLayer = dr.class_layer;
                string Title = dr.title;

                if (ClassLayer == 1)
                {
                    categoryList.Add(new SelectListItem() { Text = Title, Value = Id });
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    categoryList.Add(new SelectListItem() { Text = Title, Value = Id });
                }
            }
            ViewData["categoryList"] = categoryList;
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            NetCoreCMS.Models.Shop model = _shop.GetModel(_id);
            ViewData["model"] = model;
            string username = "未设置";
            var user = _users.GetModel(model.user_id);
            if(user!=null)
            {
                username = user.user_name;
            }
            ViewBag.username = username;
            //绑定图片相册
            if (!string.IsNullOrEmpty(model.img_url))
            {
                string filename = model.img_url.Substring(model.img_url.LastIndexOf("/") + 1);
                if (filename.StartsWith("thumb_"))
                {
                    ViewBag.hidFocusPhoto = model.img_url; //封面图片
                }
            }
        }
        #endregion

        #region 保存远程图片到本地=======================
        private string AutoRemoteImageSave(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return string.Empty;
            }
            Common.UpLoad upload = new Common.UpLoad(_env.WebRootPath, sysConfig);
            Regex reg = new Regex("IMG[^>]*?src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^\']*)')", RegexOptions.IgnoreCase);
            MatchCollection m = reg.Matches(content);
            foreach (Match math in m)
            {
                string imgUri = math.Groups[1].Value;
                if (imgUri.StartsWith("https"))
                {
                    string newImgPath = upload.RemoteSaveAs(imgUri);
                    if (newImgPath != string.Empty)
                    {
                        content = content.Replace(imgUri, newImgPath);
                    }
                }
            }
            return content;
        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd(string txtContent)
        {
            bool result = false;
            NetCoreCMS.Models.Shop model = new NetCoreCMS.Models.Shop();

            model.category_id = CMSRequest.GetFormInt("ddlCategoryId", 0, HttpContext);
            model.shopname = CMSRequest.GetFormString("txtShopname", HttpContext).Trim();
            string username = CMSRequest.GetFormString("txtUsername", HttpContext).Trim();
            var user=_users.GetModel(username);
            if(user!=null)
            {
                model.user_id = user.id;
                _users.UpdateField(user.id, "is_shop=1");
            }
            model.is_supply = CMSRequest.GetFormString("cbSupply", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_lock = CMSRequest.GetFormString("cbLock", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_top = CMSRequest.GetFormString("cblItem_1", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_red = CMSRequest.GetFormString("cblItem_2", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_hot = CMSRequest.GetFormString("cblItem_3", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_slide = CMSRequest.GetFormString("cblItem_4", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.img_url = CMSRequest.GetFormString("txtImgUrl", HttpContext);
            model.mobile = CMSRequest.GetFormString("txtMobile", HttpContext).Trim();
            model.address = CMSRequest.GetFormString("txtAddress", HttpContext).Trim();
            model.longitude = CMSRequest.GetFormFloat("txtXPoint",0, HttpContext);
            model.latitude = CMSRequest.GetFormFloat("txtYPoint",0, HttpContext);
            model.point = CMSRequest.GetFormDecimal("txtPoint", 0, HttpContext);
            model.zhekou = CMSRequest.GetFormDecimal("txtZhekou", 0, HttpContext);
            model.seo_title = CMSRequest.GetFormString("txtSeoTitle", HttpContext).Trim();
            model.seo_keywords = CMSRequest.GetFormString("txtSeoKeywords", HttpContext).Trim();
            model.seo_description = CMSRequest.GetFormString("txtSeoDescription", HttpContext).Trim();
            model.yewu = CMSRequest.GetFormString("txtYewu", HttpContext).Trim();
            //内容摘要提取内容前255个字符
            if (string.IsNullOrEmpty(CMSRequest.GetFormString("txtZhaiyao", HttpContext).Trim()))
            {
                model.zhaiyao = Utils.DropHTML(txtContent, 255);
            }
            else
            {
                model.zhaiyao = Utils.DropHTML(Request.Form["txtZhaiyao"], 255);
            }
            //是否将编辑器远程图片保存到本地
            if (sysConfig.fileremote == 1)
            {
                model.remark = AutoRemoteImageSave(txtContent);
            }
            else
            {
                model.remark = txtContent;
            }
            model.sort_id = CMSRequest.GetFormInt("txtSortId", 99, HttpContext);
            model.add_time = Utils.StrToDateTime(CMSRequest.GetFormString("txtAddTime", HttpContext).Trim());
            #region 保存相册====================
                //检查是否有自定义图片
                if (Request.Form["txtImgUrl"].FirstOrDefault().Trim() == "")
                {
                    model.img_url = Request.Form["hidFocusPhoto"];
                }
                string[] albumArr = Request.Form["hid_photo_name"];
                string[] remarkArr = Request.Form["hid_photo_remark"];
                if (albumArr != null && albumArr.Length > 0)
                {
                    List<Shop_albums> ls = new List<Shop_albums>();
                    for (int i = 0; i < albumArr.Length; i++)
                    {
                        string[] imgArr = albumArr[i].Split('|');
                        if (imgArr.Length == 3)
                        {
                            if (!string.IsNullOrEmpty(remarkArr[i]))
                            {
                                ls.Add(new Shop_albums { original_path = imgArr[1], thumb_path = imgArr[2], remark = remarkArr[i] });
                            }
                            else
                            {
                                ls.Add(new Shop_albums { original_path = imgArr[1], thumb_path = imgArr[2] });
                            }
                        }
                    }
                    model.albums = ls;
                }
                #endregion
            if (_shop.Add(model) > 0)
            {
                #region DeleteRedis
                string redisName = Request.Host.Host.ToLower().Replace(".", "_") + "_";
                using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379"))
                {
                    IDatabase db = redis.GetDatabase();
                    db.KeyDelete(redisName + "shopgeo");
                }
                #endregion
                AddAdminLog(CMSEnums.ActionEnum.Add.ToString(), "添加商户:" + model.shopname); //记录日志
                result = true;
            }
            return result;
        }
        #endregion

        #region 修改操作=================================
        [HttpPost]
        private bool DoEdit(int _id, string txtContent)
        {
            bool result = false;
            NetCoreCMS.Models.Shop model = _shop.GetModel(_id);
            model.category_id = CMSRequest.GetFormInt("ddlCategoryId", 0, HttpContext);
            model.shopname = CMSRequest.GetFormString("txtShopname", HttpContext).Trim();
            string username = CMSRequest.GetFormString("txtUsername", HttpContext).Trim();
            var user = _users.GetModel(username);
            if (user != null)
            {
                int oid = model.user_id;
                model.user_id = user.id;
                _users.UpdateField(user.id, "is_shop=1");
                //取消原主
                var oshop = _shop.GetFirstByUserId(oid);
                if(oshop==null)
                {
                    _users.UpdateField(oid, "is_shop=0");
                }
            }
            model.is_supply = CMSRequest.GetFormString("cbSupply", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_lock = CMSRequest.GetFormString("cbLock", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_top = CMSRequest.GetFormString("cblItem_1", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_red = CMSRequest.GetFormString("cblItem_2", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_hot = CMSRequest.GetFormString("cblItem_3", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.is_slide = CMSRequest.GetFormString("cblItem_4", HttpContext).ToLower().IndexOf("true") >= 0 ? 1 : 0;
            model.img_url = CMSRequest.GetFormString("txtImgUrl", HttpContext);
            model.mobile = CMSRequest.GetFormString("txtMobile", HttpContext).Trim();
            model.address = CMSRequest.GetFormString("txtAddress", HttpContext).Trim();
            model.longitude = CMSRequest.GetFormFloat("txtXPoint", 0, HttpContext);
            model.latitude = CMSRequest.GetFormFloat("txtYPoint", 0, HttpContext);
            model.point = CMSRequest.GetFormDecimal("txtPoint", 0, HttpContext);
            model.zhekou = CMSRequest.GetFormDecimal("txtZhekou", 0, HttpContext);
            model.seo_title = CMSRequest.GetFormString("txtSeoTitle", HttpContext).Trim();
            model.seo_keywords = CMSRequest.GetFormString("txtSeoKeywords", HttpContext).Trim();
            model.seo_description = CMSRequest.GetFormString("txtSeoDescription", HttpContext).Trim();
            model.yewu = CMSRequest.GetFormString("txtYewu", HttpContext).Trim();
            //内容摘要提取内容前255个字符
            if (string.IsNullOrEmpty(CMSRequest.GetFormString("txtZhaiyao", HttpContext).Trim()))
            {
                model.zhaiyao = Utils.DropHTML(txtContent, 255);
            }
            else
            {
                model.zhaiyao = Utils.DropHTML(Request.Form["txtZhaiyao"], 255);
            }
            //是否将编辑器远程图片保存到本地
            if (sysConfig.fileremote == 1)
            {
                model.remark = AutoRemoteImageSave(txtContent);
            }
            else
            {
                model.remark = txtContent;
            }
            model.sort_id = CMSRequest.GetFormInt("txtSortId", 99, HttpContext);
            model.add_time = Utils.StrToDateTime(CMSRequest.GetFormString("txtAddTime", HttpContext).Trim());
            #region 保存相册====================
                //检查是否有自定义图片
                if (Request.Form["txtImgUrl"].FirstOrDefault().Trim() == "")
                {
                    model.img_url = Request.Form["hidFocusPhoto"];
                }
                if (model.albums != null)
                {
                    model.albums.Clear();
                }
                string[] albumArr = Request.Form["hid_photo_name"];
                string[] remarkArr = Request.Form["hid_photo_remark"];
                if (albumArr != null)
                {
                    List<Shop_albums> ls = new List<Shop_albums>();
                    for (int i = 0; i < albumArr.Length; i++)
                    {
                        string[] imgArr = albumArr[i].Split('|');
                        int img_id = Utils.StrToInt(imgArr[0], 0);
                        if (imgArr.Length == 3)
                        {
                            if (!string.IsNullOrEmpty(remarkArr[i]))
                            {
                                ls.Add(new Shop_albums { id = img_id, shop_id = _id, original_path = imgArr[1], thumb_path = imgArr[2], remark = remarkArr[i] });
                            }
                            else
                            {
                                ls.Add(new Shop_albums { id = img_id, shop_id = _id, original_path = imgArr[1], thumb_path = imgArr[2] });
                            }
                        }
                    }
                    model.albums = ls;
                }
                #endregion
            if (_shop.Update(model, _env.WebRootPath))
            {
                #region DeleteRedis
                string redisName = Request.Host.Host.ToLower().Replace(".", "_") + "_";
                using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379"))
                {
                    IDatabase db = redis.GetDatabase();
                    db.KeyDelete(redisName + "shopgeo");
                } 
                #endregion
                AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "修改商户:" + model.shopname); //记录日志
                result = true;
            }
            return result;
        }
        #endregion
    }
}
